"use strict"

export default class Touch {
  /**
   * 构造器
   * @param map 地图对象
   * @param layerId 图层id
   * @param callback 长按或点击回调函数
   */
  constructor(map,layerId,callback,timeValue=1000) {
    this.timeValue=timeValue;//长按时间阈值
    this.layerId=layerId;
    this.map=map;
    this.callback=callback;
    this.isLongTouch=false;//是否是长按事件

    this.startEvent=(e)=>{
      this._clearTimer();
      let data = e.features[0];
      this.timer=setTimeout((e)=>{
        if(this.callback){
          //长按回调
          this.callback({
            type:"LongTouch",
            data:data
          })
        }
        this.isLongTouch=true;
      },this.timeValue)
      e.preventDefault();
    };
    this.map.on("touchstart", this.layerId, this.startEvent);


    this.stopEvent=(e)=>{
      if(e.type=="touchend"&&!this.isLongTouch){
        //普通点击回调
        let data = e.features[0];
        this.callback({
          type:"Touch",
          data:data
        })
      }
      this._clearTimer();
      e.preventDefault();
    };


    this.map.on("touchmove", this.layerId, this.stopEvent);
    this.map.on("touchend",  this.layerId, this.stopEvent);
  }

  /**
   * 清理计时器
   * @private
   */
  _clearTimer(){
    if(this.timer){
      clearTimeout(this.timer);
      this.timer=null;
      this.isLongTouch=false;
    }
  }

  /**
   * 移除长按事件
   */
  close(){
    this._clearTimer();
    this.map.off("touchstart", this.layerId, this.startEvent);
    this.map.off("touchmove", this.layerId, this.stopEvent);
    this.map.off("touchend",  this.layerId, this.stopEvent);
  }
}
